package com.kedacom.demo.websocket.rpc;

import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

@ClientEndpoint(configurator = AbstractRPCWebSocketClient.ClientConfigurator.class)
public class RPCWebSocketClient extends AbstractRPCWebSocketClient {

	public RPCWebSocketClient() {
		super();
	}

	public RPCWebSocketClient(String wsServerUrl) {
		super(wsServerUrl);
	}

	/** 处理推送消息 */
	public void processPushMessage(String message) {
		// TODO 处理推送消息
	}

	/* 以下带注解的方法需要在子类中进行申明，否则无法正常处理相应消息 */
	@OnOpen
	public void onOpen(Session session) {
		super.onOpen(session);
	}

	@OnMessage
	public void onMessage(String message) {
		super.onMessage(message);
	}

	@OnClose
	public void onClose(CloseReason reason) {
		super.onClose(reason);
	}

	@OnError
	public void onError(Throwable throwable) {
		super.onError(throwable);
	}

	public static void main(String[] args) throws InterruptedException {
		String url = "ws://localhost:8080/demo-websocket/websocket/rpc";
		// String url = "ws://172.16.186.246:8080/demo-websocket/websocket/rpc";

		RPCWebSocketClient rpcWebSocketClient = new RPCWebSocketClient(url);
		rpcWebSocketClient.connect();

		for (int i = 0; i < 1000; i++) {
			try {
				Response response = rpcWebSocketClient.request("type1", "Hi", Response.class);
				if (response != null) {
					System.out.println(response.getData());
				}
			} catch (ConnectionErrorException e) {
				e.printStackTrace();
			}
			Thread.sleep(2000);
		}

		Thread.currentThread().join();
		rpcWebSocketClient.destroy();
	}

}
